package d5_stream;

import org.junit.Test;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;

public class t7server {
    public static void main(String[] args) throws Exception {
        System.out.println("-------------------------------------------服务端启动------------------------------------------");
        ServerSocketChannel ssChannel = ServerSocketChannel.open();//开启系统通道
        ssChannel.configureBlocking(false);//非阻塞
        ssChannel.bind(new InetSocketAddress(9999));//添加端口
        Selector selector = Selector.open();//选择器建立
        ssChannel.register(selector, SelectionKey.OP_ACCEPT);//选择器登记通道
        while (selector.select() > 0) {
            Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();//建立选择器属性的迭代器
            while (iterator.hasNext()) {
                SelectionKey key = iterator.next();//定义选择键
                if (key.isAcceptable()) {//调用选择器方法，判断接入事件为写入事件，服务器接入
                    SocketChannel schannel = ssChannel.accept();
                    schannel.configureBlocking(false);
                    schannel.register(selector, SelectionKey.OP_READ);
                }else if(key.isReadable()){//判断事件为读取事件
                    SocketChannel schannel = (SocketChannel) key.channel();//
                    ByteBuffer buffer = ByteBuffer.allocate(1024);
                    int len = 0;
                    while(( len = schannel.read(buffer))>0){
                        buffer.flip();
                        System.out.println(new String(buffer.array(),0,len));
                        buffer.clear();
                    }
                }
                iterator.remove();
            }
        }
    }
}
